//
//  MessageDatabaseManager.m
//  HuaZiChatDemo
//
//  Created by huazi on 15-4-8.
//  Copyright (c) 2015年 huifu. All rights reserved.
//

#import "MessageDatabaseManager.h"
#import <sqlite3.h>
#define kMessageDatabase  @"MessageDatabase.sqlite3"
@interface MessageDatabaseManager ()
{
    sqlite3 *Database;
}
@end

@implementation MessageDatabaseManager
- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSFileManager *fileManager =[NSFileManager defaultManager];
//    if (![fileManager fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", kMessageDatabase,[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]]])
//    {
//        NSError *error;
//        [fileManager copyItemAtPath:[[NSBundle mainBundle] pathForResource:@"citys.rdb" ofType:nil] toPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@", kMessageDatabase,[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]] error:&error];
//    }
    return [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", kMessageDatabase]];
    
}
+(MessageDatabaseManager *)shareMessageDatabaseManager {
    static MessageDatabaseManager *_messageDatabaseManager =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _messageDatabaseManager =[[MessageDatabaseManager alloc] init];
    });
    return _messageDatabaseManager;
}
-(instancetype)init {
    if (self =[super init]) {
        
    }
    return self;
}
// 执行非查询的 sql 语句，后关闭数据库
- (void)execSql:(NSString *)sql
{
    //   下面的语句是打开数据库，如果这个路径没有该数据库，就生成一个
    if (sqlite3_open([[self dataFilePath] UTF8String], &Database)
        != SQLITE_OK) {
        sqlite3_close(Database);
        NSAssert(0, @"Failed to open database");
    }
    char *err;
    if (sqlite3_exec(Database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(Database);
        DLog(@"数据库操作数据失败!");
    }
    sqlite3_close(Database);
}
/*
-(NSInteger )querySessionTableExistsession:(NSString *)querysql
{
    if (sqlite3_open([[self dataFilePath] UTF8String], &Database)
        != SQLITE_OK) {
        sqlite3_close(Database);
        NSAssert(0, @"Failed to open database");
    }
    NSInteger returnInteger;
    //    querysql 未要执行的查询语句
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(Database, [querysql UTF8String],-1, &statement, nil) == SQLITE_OK)
    {
        
        //    SQLITE_ROW ＝＝100；
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            
            //    statement后面的数字 n 表示是第（n+1）个字段的信息
            //    int row = sqlite3_column_int(statement, 0);
            returnInteger =(NSInteger)sqlite3_column_int(statement, 0);
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(Database);

    return returnInteger;
}
-(NSMutableArray *)queryMessagesFromSessionTable:(NSString *)querysql
{
    if (sqlite3_open([[self dataFilePath] UTF8String], &Database)
        != SQLITE_OK) {
        sqlite3_close(Database);
        NSAssert(0, @"Failed to open database");
    }
    NSMutableArray *temparrSession =[[NSMutableArray alloc] init];
    
    
    //    querysql 未要执行的查询语句
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(Database, [querysql UTF8String],-1, &statement, nil) == SQLITE_OK)
    {
        
        //    SQLITE_ROW ＝＝100；
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            
            //    statement后面的数字 n 表示是第（n+1）个字段的信息
            //    int row = sqlite3_column_int(statement, 0);
//            userId TEXT,photoUrl TEXT,nickName TEXT, content TEXT, sendTime TEXT
            char *rowData1 = (char *)sqlite3_column_text(statement, 1);
            NSString *Value1 = [[NSString alloc]
                                initWithUTF8String:rowData1];
            char *rowData2 = (char *)sqlite3_column_text(statement, 2);
            NSString *Value2 = [[NSString alloc]
                                initWithUTF8String:rowData2];
            char *rowData3 = (char *)sqlite3_column_text(statement, 3);
            NSString *Value3 = [[NSString alloc]
                                initWithUTF8String:rowData3];
            char *rowData4 = (char *)sqlite3_column_text(statement, 4);
            NSString *Value4 = [[NSString alloc]
                                initWithUTF8String:rowData4];
            char *rowData5 = (char *)sqlite3_column_text(statement, 5);
            NSString *Value5 = [[NSString alloc]
                                initWithUTF8String:rowData5];
            NSDictionary *tempdic =[NSDictionary dictionaryWithObjectsAndKeys:Value1,@"userId",Value2,@"photoUrl",Value3,@"nickName",Value4,@"content",Value5,@"sendTime",nil];
            Session *_session =[[Session alloc] initWithDic:tempdic];
            [temparrSession addObject:_session];
            
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(Database);
    return temparrSession;
}
*/
@end
